package com.mudrov.runner;
import com.mudrov.anagram.core.AnagramStorage;
import org.apache.log4j.Logger;
import com.mudrov.anagram.core.Anagram;
import com.mudrov.anagram.core.HashSetCollection;
import com.mudrov.anagram.helpers.FilePiecedReader;

import java.io.*;
import java.util.TreeSet;

public class Runner {
    private static org.apache.log4j.Logger log = Logger
            .getLogger(Runner.class);
    private static String fileName;
    private static String fileNameToOut;

    public static void main(String[] args) {
        int lineNumbers = 300000;
        readDataInput();
        log.info("Starting evaluation...");
        TreeSet<HashSetCollection> listOfAllAnagrams = getHashSetCollections(lineNumbers);
        log.info("Writing results...");
        OutputResult(fileNameToOut, listOfAllAnagrams);
        log.info("Done!");
    }

    private static TreeSet<HashSetCollection> getHashSetCollections(int lineNumbers) {
        TreeSet<HashSetCollection> listOfAllAnagrams;
        try (FilePiecedReader reader = new FilePiecedReader(fileName, lineNumbers)) {
            Anagram<HashSetCollection> anagram = new AnagramStorage(reader);
            listOfAllAnagrams = (TreeSet<HashSetCollection>) anagram.getAnagramList();
        }
        return listOfAllAnagrams;
    }

    private static void readDataInput() {
        BufferedReader readerInputData = new BufferedReader(new InputStreamReader(System.in));
        do {
            System.out.println("Please enter input file name: ");
            try {
                fileName = readerInputData.readLine();
                File fileToRead = new File(fileName);
                if (!fileToRead.exists() || fileToRead.isDirectory())
                    continue;
                System.out.println("Please enter output file name: ");
                fileNameToOut = readerInputData.readLine();

            } catch (IOException e) {
                continue;
            }
            break;
        } while (true);
    }

    private static void OutputResult(String fileNameToOut, TreeSet<HashSetCollection> listOfAllAnagrams) {
        try (PrintWriter writer = new PrintWriter(fileNameToOut)) {
            for (HashSetCollection myAnagrams : listOfAllAnagrams) {
                if (myAnagrams.getAnagramList().size() < 2)
                    continue;
                for (String currentAnagram : myAnagrams.getAnagramList()) {
                    writer.print(currentAnagram + ", ");
                }
                writer.println();
            }
        } catch (FileNotFoundException e) {
            log.fatal("Cannot out result ;(");
        }
    }

}
